package com.hunter.lucene.util.search;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.spell.Dictionary;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

import com.hunter.lucene.util.config.LuceneException;

public class SuggestionConsult {
	private SpellChecker spellChecker = null;
	private Dictionary dictionary = null;

	public SuggestionConsult(Directory directory, String fieldName)
			throws LuceneException {
		try {
			spellChecker = new SpellChecker(new RAMDirectory());
			dictionary = new LuceneDictionary(
					IndexReader.open(directory, true), fieldName);
			spellChecker.indexDictionary(dictionary);
		} catch (IOException e) {
			throw new LuceneException(e);
		}
	}

	/**
	 * 重新初始化
	 * 
	 * @throws LuceneException
	 */
	public void reinit() throws LuceneException {
		try {
			spellChecker.indexDictionary(dictionary);
		} catch (IOException e) {
			throw new LuceneException(e);
		}
	}

	public String[] suggest(String similarWord, int maxLenght)
			throws LuceneException {
		try {
			return spellChecker.suggestSimilar(similarWord, maxLenght);
		} catch (IOException e) {
			throw new LuceneException(e);
		}
	}
}
